NAME = tn9k-blink-led
INC = ../common
RTL = rtl
BOARD = tangnano9k
READ_VERILOG += -p "read_verilog -sv $(RTL)/$(NAME).v"
DEPS += $(RTL)/$(NAME).v
READ_VERILOG += -p "read_verilog -sv src/gowin_rpll/gowin_rpll.v"
DEPS += src/gowin_rpll/gowin_rpll.v

CST = $(RTL)/$(NAME).cst
FREQ = 27
DEVICE_PART     := GW1NR-LV9QN88PC6/I5
DEVICE_PACK     := GW1N-9C
DEVICE_FAMILY   := GW1N-9C
#
FLASH_METHOD := $(shell cat flash_method 2> /dev/null)
UPLOAD_METHOD := $(shell cat upload_method 2> /dev/null)

PATH_TO_PNR = ~/school/tools/yosys_all/nextpnr
PNR = nextpnr-gowin
.PHONY: clean
all: $(NAME).fs


.PHONY: test_src
test_src:
	echo $(READ_VERILOG)

fw: $(NAME).fs

$(NAME).fs: $(CST) $(DEPS)
	echo "Start build " $(NAME).fs
	echo $(READ_VERILOG)
	yosys -g -p "verilog_defaults -add -I$(INC)" $(READ_VERILOG) -p "synth_gowin -json $(NAME).json -top led"
	$(PATH_TO_PNR)/$(PNR) --enable-globals --freq $(FREQ) --device $(DEVICE_PART) --family $(DEVICE_FAMILY) --json $(NAME).json --write $(NAME).pack --cst $(CST)
	gowin_pack -d $(DEVICE_PACK) -o $@ $(NAME).pack

.PHONY: prog
prog: $(NAME).fs
	openFPGALoader -m -b tangnano9k $^


.PHONY: sim
sim: $(NAME).v $(DEPS) $(NAME)_tb.v $(shell yosys-config --datdir)/ice40/cells_sim.v
	iverilog $^ -o $(NAME)_tb.out
	./$(NAME)_tb.out
	gtkwave $(NAME)_tb.vcd $(NAME)_tb.gtkw &


.PHONY: clean
clean:
	rm -f *.fs *.bin *.json *.pack *.txt *.blif *.out *.svg *.dot *.dfu *out.config

